﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using LitJson;
using System.Net;
using System.IO;
using QinMing.Config;
using QinMing.WeixinContainer;
using QinMing.Tools;

namespace Jjlm
{
	
	public partial class GetQrCode : System.Web.UI.Page
	{

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				
                if(QinMing.Tools.QinMingTools.IsHasSQLInject(Request.QueryString["snum"]))
				{
					Response.Write("请勿非法尝试！");
					Response.End();
				}
				
				if(QinMing.Tools.QinMingTools.IsHasSQLInject(Request.QueryString["enum"]))
				{
					Response.Write("请勿非法尝试！");
					Response.End();
				}
				
				//Response.Write(HttpContext.Current.Server.MapPath("/QrCodeTg/"));
				//Response.Write(GetewmPic("1"));
				//GetewmPic("1");
				
				SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
				conn.Open();
				SqlCommand cmd = new SqlCommand();
				cmd.Connection = conn;
				
				SqlConnection conn1 = new SqlConnection(QinMingConfig.DatabaseConnStr);
				conn1.Open();
				SqlCommand cmd1 = new SqlCommand();
				cmd1.Connection = conn1;
				SqlDataReader dr1;
				
				string start_num = Request.QueryString["snum"];
				string end_num = Request.QueryString["enum"];
				for(int i = Convert.ToInt32(start_num); i <= Convert.ToInt32(end_num); i = i + 1)
				{
					cmd1.CommandText = "select * from weixin_qrcode_ticket where scene_id=" + i.ToString() + " ";
                    dr1 = cmd1.ExecuteReader();
					if (dr1.Read())
					{
						//库内已存在该scene_id的带参数二维码，不再重复生成
					}
					else
					{
						string tmpurl = GetewmPic(i.ToString());
						cmd.CommandText = "insert into weixin_qrcode_ticket (scene_id,create_time,qrcode_image_url) values(" 
							+ i.ToString() + ",getdate(),'" + tmpurl + "')";
						cmd.ExecuteScalar();						
					}
					dr1.Close();
				}
				
				cmd1.CommandText = "select max(scene_id) max_scene_id from weixin_qrcode_ticket ";
                dr1 = cmd1.ExecuteReader();
				if (dr1.Read())
				{
					lbResult.Text = "目前带参数二维码已生成总数为：" + dr1["max_scene_id"].ToString();
				}
				dr1.Close();
				
				if (conn.State == ConnectionState.Open)
				{
					conn.Close();
					conn.Dispose();
				}
				
				if (conn1.State == ConnectionState.Open)
				{
					conn1.Close();
					conn1.Dispose();
				}
			}
		}
		
		public string GetewmPic(string scene_id)  
		{  
			QinMingWeixinContainer gt=new QinMingWeixinContainer();
			string access_token = gt.GetAccessToken();
			string tocket = "";  
			string pic="";  

			string poster = "{\"action_name\": \"QR_LIMIT_SCENE\",\"action_info\": {\"scene\": { \"scene_id\": " + scene_id + " } } }";//二维码永久请求格式  
			string tockes = GetPage("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token, poster);  

			if(tockes.IndexOf("ticket") > -1)  
			{  
				JsonData bejson = JsonMapper.ToObject(tockes);  
				tocket = (String)bejson["ticket"];  
				tocket = Uri.EscapeDataString(tocket);  //TICKET必需UrlEncode  
			}  

			string Picurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + tocket;  
			 
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Picurl);  
			 
			System.Drawing.Image img = System.Drawing.Image.FromStream(req.GetResponse().GetResponseStream());  
			string newfilename = "qrcode_tg_" + scene_id + ".jpg";//二维码图片路径  
			string address = HttpContext.Current.Server.MapPath("/QrCodeTg/" + newfilename);  
			img.Save(address);  
  
			pic = "QrCodeTg/" + newfilename;  

			return pic;  
		}
		
		public static string GetPage(string posturl, string postData)  
        {  
			Stream outstream = null;  
			Stream instream = null;  
			StreamReader sr = null;  
			HttpWebResponse response = null;  
			HttpWebRequest request = null;  
			Encoding encoding = Encoding.UTF8;  
			byte[] data = encoding.GetBytes(postData);  
			// 准备请求...  
			try  
			{  
				// 设置参数  
				request = WebRequest.Create(posturl) as HttpWebRequest;  
				CookieContainer cookieContainer = new CookieContainer();  
				request.CookieContainer = cookieContainer;  
				request.AllowAutoRedirect = true;  
				request.Method = "POST";  
				request.ContentType = "application/x-www-form-urlencoded";  
				request.ContentLength = data.Length;  
				outstream = request.GetRequestStream();  
				outstream.Write(data, 0, data.Length);  
				outstream.Close();  
				//发送请求并获取相应回应数据  
				response = request.GetResponse() as HttpWebResponse;  
				//直到request.GetResponse()程序才开始向目标网页发送Post请求  
				instream = response.GetResponseStream();  
				sr = new StreamReader(instream, encoding);  
				//返回结果网页（html）代码  
				string content = sr.ReadToEnd();  
				string err = string.Empty;  
				return content;  
			}  
			catch (Exception ex)  
			{  
				string err = ex.Message;  
				return string.Empty;  
			}  
        }  

	}

}